import jwt from 'jsonwebtoken';

import { jwtSecret } from '../utils';

const whitelist = [
  '/',
  '/user/login',
  '/refresh-token',
];

// eslint-disable-next-line consistent-return
export default function authenticateToken(req, res, next) {
  console.log('-------------------------------------v2 req.url: ', req.url);
  console.log('-------------------------------------v2 req.path: ', req.path);

  // Gather the jwt access token from the request header
  if (whitelist.indexOf(req.path) >= 0) {
    console.log('不需要验证token');
    next();
  } else {
    console.log('需要验证token');

    const authHeader = req.headers.authorization;
    const token = authHeader && authHeader.split(' ')[1];

    jwt.verify(token, jwtSecret, (err, user) => {
      if (err) {
        res.sendStatus(401);
      } else {
        req.user = user;
        // console.log(user);
        next(); // pass the execution off to whatever request the client intended
      }
    });
  }
}
